import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { 
  Table, 
  Button, 
  Icon, 
  Row, 
  Col, 
  Tooltip, 
  Divider, 
  Input, 
  Popconfirm, 
  message, 
  Form, 
  Select, 
  DatePicker, 
  Dropdown, 
  Menu, 
  Switch, 
  Radio, 
  Pagination, 
  LocaleProvider, 
  Tag 
} from 'antd'
import PubSub from 'pubsub-js'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { adminsUserActions, adminsGroupActions } from 'reduxs'
import moment from 'moment'
import _ from 'lodash'
import Modal from 'kenote-react-admin-modal'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag } from 'services/utils'
import { PageNotFound } from 'components'
import history from 'store/history'
import zhCN from 'antd/lib/locale-provider/zh_CN'

const FormItem = Form.Item
const Option = Select.Option
const RangePicker = DatePicker.RangePicker
const RadioGroup = Radio.Group
const RadioButton = Radio.Button
const accessFlag = getPageFlag('/admins/user', 'access')
const createFlag = getPageFlag('/admins/user', 'create')
const editFlag = getPageFlag('/admins/user', 'edit')
const removeFlag = getPageFlag('/admins/user', 'remove')
const statusFlag = getPageFlag('/admins/user', 'status')
const userTypes = {
  ['username']: '用户名',
  ['email']: '电子邮箱',
  ['nickname']: '昵称'
}

@connect(
  state => ({
    auth                : state.Passport.auth,
    groupList           : state.AdminsGroup.listData,
    listData            : state.AdminsUser.listData,
    Options             : state.AdminsUser.options,
    getListPending      : state.AdminsUser.getListPending,
  }),
  dispatch => ({
    actions: bindActionCreators({ 
      grouplist: adminsGroupActions.getlist, 
      userlist: adminsUserActions.getlist,
      setStatus: adminsUserActions.setStatus,
      remove: adminsUserActions.remove
    }, dispatch)
  })
)
@Form.create()
class AdvancedSearchForm extends PureComponent {

  static propTypes = {
    selectedRowKeys: PropTypes.array,
  }
  
  static defaultProps = {
    selectedRowKeys: []
  }


  constructor (props) {
    super(props)
    const { Options } = props
    let userType = 'username'
    if (_.has(Options, 'email')) {
      userType = 'email'
    }
    if (_.has(Options, 'nickname')) {
      userType = 'nickname'
    }
    this.state = {
      userType
    }
  }
  
  componentDidMount () {
    this.props.actions.grouplist()
  }

  render () {
    const { groupList, Options, getListPending, listData, selectedRowKeys, auth } = this.props
    const { getFieldDecorator } = this.props.form
    let create_time = [undefined, undefined]
    if (_.has(Options, 'create_time')) {
      create_time = []
      let create_time_arr = Options.create_time.split('|')
      for (let e of create_time_arr) {
        create_time.push(moment(moment(Number(e)).format('YYYY-MM-DD HH:mm')))
      }
    }
    return (
      <Form
        className="ant-advanced-search-form"
        onSubmit={this.handleSubmit}
        >
        <div className="content">
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>添加时间</span>)}
            >
            <LocaleProvider locale={zhCN} >
              {getFieldDecorator('create_time', {
                initialValue: create_time
              })(
                  <RangePicker
                    showTime={{ format: 'HH:mm' }}
                    format="YYYY-MM-DD HH:mm"
                    />
              )}
            </LocaleProvider>
          </FormItem>
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>用户组</span>)}
            >
            {getFieldDecorator('group', {
              initialValue: _.has(Options, 'group') ? Options.group : undefined
            })(
              <Select 
                placeholder="请选择用户组..." 
                size="Small"
                mode="multiple"
                style={{ width: '650px' }}
                >
                {groupList && groupList.map((item, i) => {
                  return (
                    <Option key={i} value={item.id}>{item.name}</Option>
                  )
                })}
              </Select>
            )}
          </FormItem>
          <FormItem 
            label={(
              <span style={{ width: 80, display: 'inline-block' }}>
                <Dropdown 
                  overlay={(
                    <Menu className="app-header-menu" onClick={this.handleChangeUserType}>
                      {_.keys(userTypes).map((item, i) => {
                        return (
                          <Menu.Item className={`app-header-menu-span`}  key={item}>{userTypes[item]}</Menu.Item>
                        )
                      })}
                    </Menu>
                  )}
                  >
                  <a className="ant-dropdown-link" >
                    {userTypes[this.state.userType]} <Icon type="down" />
                  </a>
                </Dropdown>
              </span>
            )}
            >
            {getFieldDecorator('findname', {
              initialValue: Options ? (Options.email || Options.username || Options.nickname || '').replace(/\|/g, ' ') : ''
            })(
              <Input style={{ width: '350px' }} />
            )}
          </FormItem>
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>冻结</span>)}
            >
            {getFieldDecorator('freeze', {
              initialValue: _.has(Options, 'freeze') ? (Options.freeze ? '1' : '0') : '2'
            })(
              <RadioGroup>
                <RadioButton value="2">忽略</RadioButton>
                <RadioButton value="1">冻结</RadioButton>
                <RadioButton value="0">不冻结</RadioButton>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem 
            label={(<span style={{ width: 80, display: 'inline-block' }}>锁定</span>)}
            >
            {getFieldDecorator('lock', {
              initialValue: _.has(Options, 'lock') ? (Options.lock ? '1' : '0') : '2'
            })(
              <RadioGroup>
                <RadioButton value="2">忽略</RadioButton>
                <RadioButton value="1">锁定</RadioButton>
                <RadioButton value="0">不锁定</RadioButton>
              </RadioGroup>
            )}
          </FormItem>
        </div>
        <Divider style={{ marginTop: 0 }} />
        <Row>
          <Col span={20}>
            <Button type="primary" htmlType="submit" loading={getListPending}>高级查询</Button>
            <Button 
              style={{ marginLeft: 10 }} 
              onClick={this.handleClickAdd}
              disabled={getFlagValue(auth, createFlag.value, null)}
              >
              创建用户
            </Button>
            <Dropdown 
              overlay={(
                <Menu className="app-header-menu" onClick={this.handleClickBatch}>
                  <Menu.Item 
                    key={'freeze'} 
                    className={`app-header-menu-span${getFlagValue(auth, statusFlag.value, ['-disabled', ''])}`}
                    disabled={getFlagValue(auth, statusFlag.value)}
                    >
                    冻结所选账号
                  </Menu.Item>
                  <Menu.Item 
                    key={'unfreeze'}
                    className={`app-header-menu-span${getFlagValue(auth, statusFlag.value, ['-disabled', ''])}`}
                    disabled={getFlagValue(auth, statusFlag.value)}
                    >解冻所选账号
                  </Menu.Item>
                  <Menu.Divider className="app-header-menu-driver" />
                  <Menu.Item 
                    key={'lock'} 
                    className={`app-header-menu-span${getFlagValue(auth, statusFlag.value, ['-disabled', ''])}`}
                    disabled={getFlagValue(auth, statusFlag.value)}
                    >
                    锁定所选账号
                  </Menu.Item>
                  <Menu.Item 
                    key={'unlock'} 
                    className={`app-header-menu-span${getFlagValue(auth, statusFlag.value, ['-disabled', ''])}`}
                    disabled={getFlagValue(auth, statusFlag.value)}
                    >
                    解锁所选账号
                  </Menu.Item>
                  <Menu.Divider className="app-header-menu-driver" />
                  <Menu.Item 
                    key={'remove'} 
                    className={`app-header-menu-span${getFlagValue(auth, removeFlag.value, ['-disabled', ''])}`} 
                    disabled={getFlagValue(auth, removeFlag.value)}
                    >
                    删除所选账号
                  </Menu.Item>
                </Menu>
              )}
              trigger="click"
              disabled={selectedRowKeys.length === 0}
              >
              <a className="ant-dropdown-link" style={{ marginLeft: 30 }}>
                批量操作 <Icon type="down" />
              </a>
            </Dropdown>
          </Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <Tooltip title="刷新">
              {listData && (
                <Button shape="circle" style={{ border: 0 }} onClick={() => this.props.actions.userlist(Options)}>
                  <Icon type="sync" spin={getListPending} />
                </Button>
              )}
            </Tooltip>
          </Col>
        </Row>
      </Form>
    )
  }

  handleSubmit = e => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        let options = null
        if (values.create_time) {
          let create_time = []
          for (let item of values.create_time) {
            item && create_time.push(moment(item).format('x'))
          }
          if (create_time.length > 0) {
            options = { ...options, create_time: _.join(create_time, '|') }
          }
        }
        if (values.group) {
          options = { ...options, group: _.join(values.group, '|') }
        }
        if (values.findname) {
          options = { ...options, [this.state.userType]: _.join(values.findname.split(/\s+/), '|') }
        }
        if (values.freeze !== '2') {
          options = { ...options, freeze: values.freeze === '1' }
        }
        if (values.lock !== '2') {
          options = { ...options, lock: values.lock === '1' }
        }
        this.props.actions.userlist(options)
      }
    })
  }

  handleChangeUserType = e => this.setState({ userType: e.key })

  handleClickAdd = () => {
    const { groupList } = this.props
    let list = _.filter(groupList, o => o.level < 9999)
    if (list.length === 0) {
      Modal.warning({
        title: '操作提示',
        content: '请先创建用户组！',
        onOk() {
          history.push('/admins/group')
        }
      })
      return
    }
    PubSub.publish('OPEN_MODAL', 'AddAdminsUserModal')
  }

  handleClickBatch = ({ key }) => {
    const { actions,  selectedRowKeys, Options} = this.props
    if (/(freeze)$/.test(key)) {
      let freezeSett = { 
        freeze: { name: '冻结', value: true }, 
        unfreeze: { name: '解冻', value: false } 
      }
      let freezeCell = freezeSett[key]
      Modal.confirm({
        title: '操作提示',
        content: `确定要${freezeCell.name}所选的账号吗？`,
        onOk() {
          actions.setStatus(selectedRowKeys, { freeze: freezeCell.value }, Options)
        }
      })
    }
    else if (/(lock)$/.test(key)) {
      let lockSett = { 
        lock: { name: '锁定', value: true }, 
        unlock: { name: '解锁', value: false } 
      }
      let lockCell = lockSett[key]
      Modal.confirm({
        title: '操作提示',
        content: `确定要${lockCell.name}所选的账号吗？`,
        onOk() {
          actions.setStatus(selectedRowKeys, { lock: lockCell.value }, Options)
        }
      })
    }
    else if (key === 'remove') {
      Modal.confirm({
        title: '操作提示',
        content: `确定要删除所选的账号吗？`,
        onOk() {
          actions.remove(selectedRowKeys, Options)
        }
      })
    }
  }
}

@connect(
  state => ({
    createPending       : state.AdminsUser.createPending,
    editPending         : state.AdminsUser.editPending,
    statusPending       : state.AdminsUser.statusPending,
    getListPending      : state.AdminsUser.getListPending,
    getListError        : state.AdminsUser.getListError,
    getListMessage      : state.AdminsUser.getListMessage,
    listData            : state.AdminsUser.listData,
    Options             : state.AdminsUser.options,
    auth                : state.Passport.auth,
    teams               : state.Passport.teams
  }),
  dispatch => ({
    actions: bindActionCreators({...adminsUserActions}, dispatch)
  })
)
export default class AdminsUser extends PureComponent {

  state = {
    selectedRowKeys: []
  }

  constructor (props) {
    super(props)
  }
  
  componentDidMount () {
    this.props.actions.getlist(this.props.Options)
  }
  
  componentWillReceiveProps (nextProps) {
    const { getListError, getListMessage, getListPending, statusPending } = nextProps
    if (getListPending) {
      this.setState({ selectedRowKeys: [] })
    }
  }

  render () {
    const { location, getListPending, listData, auth, teams, Options, getListError } = this.props
    const { group } = auth
    const { selectedRowKeys } = this.state
    
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '帐号管理' },
        { name: '用户管理' }
      ],
      errCode: getListError
    }
    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 100,
        fixed: 'left'
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
        width: 150,
        render: (username, record) => findKeyName('username', Options, username) ,
      },
      {
        title: '用户组',
        dataIndex: 'group',
        key: 'group',
        width: 120,
        render: (group) => (
          <Tooltip title={group.desc}>
            <span>{group.name}</span>
          </Tooltip>
        ) ,
      },
      {
        title: '团队',
        dataIndex: 'group',
        key: 'group-team',
        width: 150,
        render: (group) => (
          <span>{showTeam(group.team, teams)}</span>
        ) ,
      },
      {
        title: 'E-Mail',
        dataIndex: 'email',
        key: 'email',
        width: 250,
        render: (email) => findKeyName('email', Options, email || '--') ,
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        key: 'nickname',
        width: 150,
        render: (nickname) => findKeyName('nickname', Options, nickname || '--') ,
      },
      {
        title: '注册时间',
        dataIndex: 'createAt',
        key: 'createAt',
        width: 180,
        render: (createAt) => (<span>{moment(createAt).format('YYYY-MM-DD HH:mm:ss')}</span>) ,
      },
      {
        title: '更新时间',
        dataIndex: 'updateAt',
        key: 'updateAt',
        width: 180,
        render: (updateAt) => (<span>{moment(updateAt).format('YYYY-MM-DD HH:mm:ss')}</span>) ,
      },
      {},
      {
        title: '冻结',
        dataIndex: 'freeze',
        key: 'freeze',
        width: 80,
        render: (freeze, record) => (
          <Switch 
            checked={freeze} 
            checkedChildren="冻结" 
            unCheckedChildren="解冻"
            disabled={record.group.level === 9999 
              ? true 
              : getFlagValue(auth, statusFlag.value, null, group.level > record.group.level && getTeamFlag(record.group.team, auth))
            }
            onChange={ freeze => this.props.actions.setStatus(record._id, { freeze }, Options)}
            />
        ),
        fixed: 'right'
      },
      {
        title: '锁定',
        dataIndex: 'lock',
        key: 'lock',
        width: 80,
        render: (lock, record) => (
          <Switch 
            checked={lock} 
            checkedChildren="锁定" 
            unCheckedChildren="解锁"
            disabled={record.group.level === 9999 
              ? true 
              : getFlagValue(auth, statusFlag.value, null, group.level > record.group.level && getTeamFlag(record.group.team, auth))
            }
            onChange={ lock => this.props.actions.setStatus(record._id, { lock }, Options)}
            />
        ),
        fixed: 'right'
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        render: (text, record) => (
          <span>
            <a 
              onClick={() => {
                PubSub.publish('OPEN_MODAL', ['EditAdminsUserModal', { id: record._id }])
              }}
              disabled={getFlagValue(auth, editFlag.value, null, group.level > record.group.level && getTeamFlag(record.group.team, auth))}
              >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除吗？"
              onConfirm={() => {
                console.log('delete')
                this.props.actions.remove(record._id, Options)
              }}
              >
              <a 
                disabled={record.group.level === 9999 
                  ? true 
                  : getFlagValue(auth, removeFlag.value, null, group.level > record.group.level && getTeamFlag(record.group.team, auth))
                }
                >
                删除
              </a>
            </Popconfirm>
            {auth._id === record._id && (<Divider type="vertical" />)}
            {auth._id === record._id && (<Tag color="orange">me</Tag>)}
          </span>
        ),
        fixed: 'right'
      },
    ]
    const dataSource = getDataSource(listData, { 
      key: '_id', 
      //query: o => o.level > 1000,
      //order: [['id', 'level'], ['asc', 'desc']] 
    })
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: record => ({
        disabled: record.group.level === 9999 
          ? true 
          : !(group.level > record.group.level && getTeamFlag(record.group.team, auth)) && group.level !== 9999
      })
    }
    return (
      <CoreLayout {...options}>
        <AdvancedSearchForm selectedRowKeys={selectedRowKeys} />
        <Table 
          rowSelection={rowSelection}
          columns={columns} 
          dataSource={dataSource} 
          loading={getListPending} 
          pagination={false} 
          //bordered={true} 
          scroll={{ x: 1692 }}
          size="middle"
        />
        {Options && (
          <div style={{ textAlign: 'right', margin: '12px 0' }}>
            {Options.counts > 0 && (
              <LocaleProvider locale={zhCN} >
                <Pagination 
                  showQuickJumper 
                  current={Options.page} 
                  total={Options.counts || 0} 
                  //showTotal={(total, range) => `[${_.join(range, ' - ')}], 共 ${total} 条记录 `}
                  pageSize={Options.page_size || 0} 
                  onChange={this.handleChangePage}
                  />
              </LocaleProvider>
            )}
          </div>
        )}
      </CoreLayout>
    )
  }

  handleChangePage = (page) => {
    this.props.actions.getlist({ ...this.props.Options, page })
  }

  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys })
  }
}

const findKeyName = (name, opts, value) => {
  if (_.has(opts, name)) {
    let key = opts[name]
    let arr = value.split(new RegExp(`(${key})`))
    return (
      <span>
        {arr.map((item, i) => {
          if (key.split('|').indexOf(item) > -1) {
            return (<span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>{item}</span>)
          }
          else {
            return item
          }
        })}
      </span>
    )
  }
  return value
} 